/**
 * 基础菜单 考试管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>考试管理-考试分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search" label-suffix="：">
      <el-form-item label="分类">
        <el-input size="small" v-model="formInline.examType" clearable placeholder="输入分类名称"></el-input>
      </el-form-item>
      <el-form-item label="创建人">
        <el-input size="small" v-model="formInline.creator" clearable placeholder="输入创建人"></el-input>
      </el-form-item>
      <el-form-item label="操作">
        <el-button size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
        <el-button size="small" icon="el-icon-delete-solid" @click="clearList()">清空</el-button>
        <el-button size="small" type="info" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
        <el-button size="small" type="warning" icon="el-icon-link" @click="examList()">列表</el-button>
        <!-- <el-button size="small" type="danger" icon="el-icon-delete" @click="deleteAll(scope.$index, scope.row)">删除</el-button> -->
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="examTypeList" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="examType" label="分类名称" width="200">
      </el-table-column>
      <el-table-column sortable prop="user.name" label="创建人" width="200">
      </el-table-column>
      <el-table-column sortable prop="createTiem" label="创建时间" width="200">
      </el-table-column>
      <el-table-column sortable prop="updateTime" label="修改时间" width="200">
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="small" type="info" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" icon="el-icon-delete" @click="deleteType(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination :child-msg="pageparm" @call="callFather"></Pagination>
    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click="closeDialog" >
      <el-form label-width="100px" :model="examFrom" :rules="rules" ref="examFrom" label-suffix="：">
        <el-form-item label="分类名称" prop="examType">
          <el-input size="large" style="width:350px" v-model="examFrom.examType" auto-complete="off" clearable placeholder="请输入分类名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="large" icon="el-icon-circle-close" @click="closeDialog">取消</el-button>
        <el-button size="large" type="success" :loading="loading" icon="el-icon-circle-check" class="title" @click="submitForm('examFrom')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
export default {
  //model
  data() {
    return {

      // 分页参数
      pageparm: {
        currentPage: 1, //当前页
        pageSize: 5, //决定每页显示多少条
        total: 10 //决定总条数
      },

      //列表数据
      examTypeList: [], //分类数据

      //模糊查询返回的值
      formInline: {
        examType:"",
        creator:"",
        startPage: 1,
        limit: 5,
      },

      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      title: '添加',

      //添加的数据  编辑的数据
      examFrom: {
        id:"",
        examType:"",
        creator:""
      },
      upCreate:"",

      // rules表单验证
      rules: {
        deptName: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],
        deptNo: [{ required: true, message: '请输入部门代码', trigger: 'blur' }]
      },
      
      // userparm: [], //搜索权限
      // listData: [], //用户数据
      
      user:{}, 

      //复选框选择的数据
      multipleSelection:[],

      id:[],

    }
  },
  // 注册组件
  components: {
    Pagination
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    //分类列表
    this.getData();
    //获取当前登录人信息
    this.user = JSON.parse(localStorage.getItem('userdata'))
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 获取分类列表
    getData() {
      this.$axios.get('/api/exam/typeList',{
        params: {
          pageNum: this.pageparm.currentPage,
          pageSize: this.pageparm.pageSize,
        }
      })
      .then(res => {
        this.examTypeList = res.data.list;
        console.log('examTypeList中数据是:', res);
        this.pageparm.total = res.data.total;
        console.log("全列表总数据",this.pageparm.total);
      })
      .catch((e) => {
        console.log('列表获取数据失败');
      });
    },

  // 搜索事件
    search() {
      this.pageparm.currentPage=1;
      this.$axios.get('/api/exam/search',{
        params: {
          examType: this.formInline.examType,
          creator: this.formInline.creator,
          pageNum: this.formInline.startPage,
          pageSize: this.formInline.limit
        }
      })
      .then(res => {
        this.examTypeList = res.data.list;
        console.log('模糊查询获取的数据是:', this.examTypeList);
        this.pageparm.total = res.data.total;
        console.log('模糊查询数据:', this.pageparm.total);
      })
      .catch((e) => {
        console.log('模糊查询获取数据失败');
      });
    },

//====================================批量删除（未完成）=====================================
    //复选框选择
    handleSelectionChange(val){
      this.multipleSelection = val;
      console.log("复选框选择数据：",this.multipleSelection)
      this.id = this.multipleSelection.id;
      for(let i=1 ; i<this.multipleSelection.length ; i++){
        console.log("长度：",this.multipleSelection.length)
        console.log("选择的id：",this.multipleSelection[i].id)
        this.id += this.multipleSelection[i].id
        console.log("相应的id",this.id);
      }
      this.id = this.id.substring(0,this.multipleSelection.length-1)
      console.log("最终有哪些值",this.id)
    },

    //批量删除
    deleteAll(){
      this
      .$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        for(let i=0 ; i<this.multipleSelection.length ; i++){
          let ids = this.multipleSelection[i].id
        this.$axios
        .get("/api/exam/delAll" , {
        params: {
          id: ids
        }
      })
        .then(res => {
          console.log("数据",res)
          if (res.data=='success') {
            this.$message({
              type: 'success',
              message: '考试分类已删除!'
              })
              this.getData()
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('考试分类删除失败，请稍后再试！')
        })
        }
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
//==============================================================================
    //显示编辑界面
    handleEdit: function(index, row) {
      console.log(row);
      this.editFormVisible = true
      if (row != undefined && row != 'undefined') {
        this.title = '修改'
        this.examFrom.id = row.id;
        this.examFrom.examType = row.examType;
      } else {
        this.title = '添加'
        this.examFrom.id = '';
        this.examFrom.examType = '';
      }
    },

    //日期格式化
    formatTime(date) { 
      let year = date.getFullYear()
      let month= date.getMonth()+ 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      let day=date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      let hours=date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      let minutes=date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      let seconds=date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      // 拼接
      return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
    },

    // 编辑、增加页面保存方法
    submitForm(editData) {
      this.$refs[editData].validate(valid => {
        if (valid) {
          if(this.examFrom.id == ''){
            //添加=======================================
            this.examFrom.creator = this.user.id;
            this.$axios.post("/api/exam/add",this.examFrom)
          .then(res=>{
            if(res.data == 'success'){
              this.editFormVisible = false
              this.loading = false
              this.getData()
              this.$message({
                type: 'success',
                message: '添加成功！'
              })
            }else{
              this.editFormVisible = false
              this.loading = false
              this.$message.error('添加失败，请稍后再试！')
            }
          })
          .catch(err => {
              this.editFormVisible = false
              this.loading = false
              this.$message.error('添加失败，请稍后再试！')
            })
          }else{
            //编辑=====================================
            this.$axios.post("/api/exam/up",this.examFrom)
          .then(res=>{
              this.editFormVisible = false
              this.loading = false
              this.getData()
              this.$message({
                type: 'success',
                message: '考试修改成功！'
              })
          })
          .catch(err => {
              this.editFormVisible = false
              this.loading = false
              this.$message.error('修改失败，请稍后再试！')
            })
          }
        } else {
          return false
        }
      })
    },

    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage;
      this.formInline.limit = parm.pageSize;
      this.pageparm.currentPage = parm.currentPage;
      this.pageparm.pageSize = parm.pageSize;
      this.getData();
    },
    
    // 删除一行数据
    deleteType(index, row) {
      this
      .$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        this.$axios
        .get("/api/exam/del" , {
        params: {
          id: row.id
        }
      })
        .then(res => {
          console.log("数据",res)
          if (res.data=='success') {
            this.$message({
              type: 'success',
              message: '考试分类已删除!'
              })
              
        //分类删除的同时，相应分类的考试也删除
          this.$axios.get("/api/infor/id",{
            params:{
              id: row.id
            }
          })
          .then(res => {
            //判断该分类是否有考试信息
            if(res.data.length != 0){
              this.$axios
                .get("/api/infor/del" , {
                params: {
                  typeId: row.id
                }
              })
                .then(res => {
                  console.log("数据",res)
                  if (res.data=='success') {
                    this.$message({
                      type: 'success',
                      message: '相应考试已删除!'
                      })
                      this.getData()
                  } else {
                    this.$message({
                      type: 'info',
                      message: res.msg
                    })
                  }
                })
                .catch(err => {
                  this.loading = false
                  this.$message.error('考试删除失败，请稍后再试！')
                })
            }else{
              this.loading = false
              this.$message.error('没有对应考试信息！')
            }
          })
          .catch(err => {
            this.loading = false
            this.$message.error('没有对应考试信息！')
          })    
        //=========================================
            this.getData()
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('考试分类删除失败，请稍后再试！')
        })
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
    },
    
    //考试列表
    examList(){
      this.$router.push('./examlist');
    },

    //清空
    clearList(){
      this.formInline.examType="";
      this.formInline.creator="";
    },
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>
